#include "FlowerPot.h"
#include "Engine.h"
#include "StageManager.h"

const char FlowerPot::className[] = "FlowerPot";

#define method(class, name) {#name, &class::name}

Lunar<FlowerPot>::RegType FlowerPot::methods[] = {
	method(FlowerPot, load),
};

FlowerPot::FlowerPot() {
}

FlowerPot::FlowerPot(lua_State* L) {
}

FlowerPot::~FlowerPot() {
}

void FlowerPot::init() {
}

int FlowerPot::load(lua_State* L) {
	// Read flowerpot position
	float x,y,z;
	std::string modelFile = "../data/mesh/";

	int nbArgs = lua_gettop(L);
	if (nbArgs == 4 && lua_isnumber(L,1) && lua_isnumber(L,2) && lua_isnumber(L,3) && lua_isstring(L,4)) {
		x = lua_tonumber(L,1);
		y = lua_tonumber(L,2);
		z = lua_tonumber(L,3);
		modelFile += lua_tostring(L,4);
	}
	else {
		std::cerr << "FlowerPot loading : wrong parameters" << std::endl;
		return 0;
	}

	// Load flowerpot model
	m_ptransform = new osg::PositionAttitudeTransform;
	osg::Node* pot = osgDB::readNodeFile(modelFile);

	
	m_ptransform->addChild(pot);
	m_ptransform->setPosition(osg::Vec3(x, y, z));
	m_ptransform->setAttitude(osg::Quat(osg::PI_2, osg::Vec3d(1.0, 0.0, 0.0)));
	ComputeBoundingBox b2;
    pot->accept(b2);
	// Declare instance of class to record state of keyboard
	m_pkeyState = new KeyboardState();

	// Set up the tank update callback
	//  pass the constructor a pointer to our tank input device state
	//  that we declared above.
	m_ptransform->setUpdateCallback(new FlowerPotActionCallback(m_pkeyState));

	// The constructor for our event handler also gets a pointer to
	//   our tank input device state instance
	KeyboardEventHandler* flowerEventHandler = new KeyboardEventHandler(m_pkeyState);

	// Add our event handler to the list
	Engine::getInstance().getViewer().addEventHandler(flowerEventHandler);

	StageManager::getInstance().getRootNode()->addChild(m_ptransform);

	return 0;
}

void FlowerPotActionCallback::operator()(osg::Node* node, osg::NodeVisitor* nv) {
	osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*> (node);
	if(pat) {
		if ((m_pkeyState->m_key == osgGA::GUIEventAdapter::KEY_Space)&&(m_pkeyState->m_keydown)) {
			osg::Vec3d pos = pat->getPosition();
			osg::Vec3d player = StageManager::getInstance().getCurrentStage()->getPlayer()->getPosition();
			float dist = (pos-player).length();

			if(dist < 4.) {
				//std::cout << "FLOWER POT ACTION!" << std::endl;
				if (!StageManager::getInstance().getCurrentStage()->getPlayer()->isHidded())
					StageManager::getInstance().getCurrentStage()->getPlayer()->setHidded(true);
				else
					StageManager::getInstance().getCurrentStage()->getPlayer()->setHidded(false);
				m_pkeyState->m_keydown = false;
			}
		}
	}
	traverse(node, nv); 
}